//
//  DetailViewController.m
//  CWeekly
//
//  Created by Tiger on 12-4-18.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"
#import "DataTools.h"
#define bottomViewheight 200

#define KeyboardHeight_v 262
#define KeyboardHeight 352
//#define keyboardH  ((self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)?352:262)


#define showType 0//web＋动画是0,scrollview是1
//#define CURRENT_IOS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
#if __IPHONE_OS_VERSION_MAX_ALLOWED >__IPHONE_4_2
@implementation UINavigationBar(CustomBackground)
- (UIImage *)barBackground{
    if (self.frame.size.width >1000) {
        return [UIImage imageNamed:@"topbar.png"];
    }
    else {
        return [UIImage imageNamed:@"topbar_v.png"];

    }
}

- (void)didMoveToSuperview{
    //iOS5 only
    if ([self respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)])
    {
        [self setBackgroundImage:[self barBackground] forBarMetrics:UIBarMetricsDefault];
    }
}

- (void)drawRect:(CGRect)rect{
    [[self barBackground] drawInRect:rect];
}
@end
#else

#endif

@interface DetailViewController ()

@end

@implementation DetailViewController
@synthesize  mgid;
#if showType
static int webCount=3;
#endif
static int currentPage;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dataArray=[[NSMutableArray alloc]init];
        thumbArray=[[NSMutableArray alloc] init];
        collectionList = [[NSMutableArray alloc] init];
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShown:) name:UIKeyboardDidShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardMiss) name:UIKeyboardDidHideNotification object:nil];

    }
    return self;
}

- (void)addCollection
{
    [collectionList removeAllObjects];
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    [collectionList addObjectsFromArray:[delegate getCollection]];
    
    BOOL isHave = NO;
    for (int i=0; i<[collectionList count]; i++) {
        NSDictionary *dic = [collectionList objectAtIndex:i];
        NSString *old_mgId = [dic objectForKey:@"mgId"];
        NSString *old_num = [dic objectForKey:@"num"];
        
        NSString *current_num = [NSString stringWithFormat:@"%d",currentPage];
        
        if ([old_mgId isEqualToString:[NSString stringWithFormat:@"%@",mgid]] && [old_num isEqualToString:current_num]) {
            isHave = YES;
            break;
        }
    }
    
    if (!isHave) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *time = [DataTools stringOfDate:[NSDate date] formatString:@"yyyy年MM月dd日 HH:mm"];
        [dic setObject:time forKey:@"time"];
        [dic setObject:[NSString stringWithFormat:@"%@",mgid] forKey:@"mgId"];
        [dic setObject:[NSString stringWithFormat:@"%d",currentPage] forKey:@"num"];
        [dic setObject:((Page *)[dataArray objectAtIndex:currentPage]).t_thumbnails forKey:@"t_thumbnails"];
        [collectionList addObject:dic];
        
        [delegate setCollectionList:collectionList];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ReflashShoucangList" object: nil];
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"提示" 
                                                       message: @"成功添加到收藏" 
                                                      delegate: self 
                                             cancelButtonTitle: @"确定" 
                                             otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"提示" 
                                                       message: @"已存在于收藏列表中" 
                                                      delegate: self 
                                             cancelButtonTitle: @"确定" 
                                             otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

- (void)dealloc
{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
    [htmlView release];
    [pov release];
    [mgid release];
    [thumbArray release];
    [dataArray release];
    [ascrollView release];
    [collectionList release];
    [super dealloc];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated ];
    [self.navigationController.navigationBar setHidden:YES];
}

-(void)keyboardMiss{
//    float keyboardH=(self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)?352:262;
//
//    [mark reFreshFrame:CGRectMake(0, 60, viewWidth, htmlView.frame.size.height-keyboardH-60)];
}
//
//- (void)keyboardDidShown:(NSNotification*)aNotification
//{
//    NSDictionary* info = [aNotification userInfo];
//    keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; //获取键盘高度
//    NSLog(@"%f,%f",htmlView.frame.size.height,keyboardSize.height);
////    [mark reFreshFrame:CGRectMake(0, 60, viewWidth, htmlView.frame.size.height-keyboardSize.height-60)];
//
//}

-(void)viewWidth:(UIInterfaceOrientation)interfaceOrientation{
    if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        viewWidth=1024.0f;
    }else {
        viewWidth=768.0f;
    }

}

-(void)initTopView{
        topview=[[UIView alloc] init];
        topview.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.6];
        topview.frame=CGRectMake(0, 0, viewWidth, 55);

        UIButton* home=[UIButton buttonWithType:UIButtonTypeCustom];
        home.frame=CGRectMake(40, 0, 40, 55);
        home.showsTouchWhenHighlighted=YES;
        [home setImage:[UIImage imageNamed:@"home.png"] forState:UIControlStateNormal];
        [home setImage:[UIImage imageNamed:@"home_s.png"] forState:UIControlStateHighlighted];
        [home addTarget:self action:@selector(popView) forControlEvents:UIControlEventTouchUpInside];
        [topview addSubview:home];

        UIButton* listbtn=[UIButton buttonWithType:UIButtonTypeCustom];
        listbtn.frame=CGRectMake(90, 0, 40, 55);
        listbtn.showsTouchWhenHighlighted=YES;
        [listbtn addTarget:self action:@selector(showList) forControlEvents:UIControlEventTouchUpInside];
        [listbtn setImage:[UIImage imageNamed:@"list.png"] forState:UIControlStateNormal];
        [listbtn setImage:[UIImage imageNamed:@"list_s.png"] forState:UIControlStateHighlighted];
        [topview addSubview:listbtn];
        
        UIButton* share=[UIButton buttonWithType:UIButtonTypeCustom];
        [share setImage:[UIImage imageNamed:@"share.png"] forState:UIControlStateNormal];
        share.tag=111;
        [share setImage:[UIImage imageNamed:@"share_s.png"] forState:UIControlStateHighlighted];
        share.showsTouchWhenHighlighted=YES;
        [share addTarget:self action:@selector(showShare) forControlEvents:UIControlEventTouchUpInside];
        [topview addSubview:share];
    
    UIButton*markbtn=[UIButton buttonWithType:UIButtonTypeCustom];
    markbtn.tag=222;
    [markbtn addTarget:self action:@selector(markEvent) forControlEvents:UIControlEventTouchUpInside];
    markbtn.frame=CGRectMake(viewWidth-140, 0, 40, 55);
    [markbtn setImage:[UIImage imageNamed:@"remark.png"] forState:UIControlStateNormal];
    [markbtn setImage:[UIImage imageNamed:@"remark.png_s"] forState:UIControlStateHighlighted];
    [topview addSubview:markbtn];
    
    share.frame=CGRectMake(viewWidth-80, 0, 40, 55);
    
    UIButton*add=[UIButton buttonWithType:UIButtonTypeCustom];
    add.tag=333;
    add.frame=CGRectMake(viewWidth-200, 0, 40, 55);

    [add addTarget:self action:@selector(addFavouret) forControlEvents:UIControlEventTouchUpInside];
    [add setImage:[UIImage imageNamed:@"addmark.png"] forState:UIControlStateNormal];
    [add setImage:[UIImage imageNamed:@"addmark_s.png"] forState:UIControlStateHighlighted];
    [topview addSubview:markbtn];
    [topview addSubview:add];
    [self.view addSubview:topview];
    [self.view bringSubviewToFront:topview];
    [topview release];

}

-(void)showShare{
    
    UIViewController* shareViewController=[[UIViewController alloc] init];
    shareViewController.view.frame=CGRectMake(0, 0, 220, 120);
    UIButton* but=[UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:@"share_email.png"] forState:UIControlStateNormal];
    but.frame=CGRectMake(0,5, 210, 35);
    [shareViewController.view addSubview:but];
    
    but=[UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:@"share_sina.png"] forState:UIControlStateNormal];
    but.frame=CGRectMake(0,45, 210, 35);
    [shareViewController.view addSubview:but];
    
    but=[UIButton buttonWithType:UIButtonTypeCustom];
    [but setImage:[UIImage imageNamed:@"share_tencent.png"] forState:UIControlStateNormal];
    but.frame=CGRectMake(0, 85, 210, 35);
    [shareViewController.view addSubview:but];

    if (pov==nil) {
        pov=[[UIPopoverController alloc] initWithContentViewController:shareViewController];
        pov.popoverContentSize=CGSizeMake(210, 130);
    }
    if (pov.popoverVisible) {
        [pov dismissPopoverAnimated:YES];
    }
    
    [pov presentPopoverFromRect:[topview viewWithTag:111].frame inView:topview permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];

    
}


-(void)addFavouret{
    [self addCollection];
}
-(void)markEvent{
    if (mark.alpha) {
        mark.alpha=0;
        [mark.tv resignFirstResponder];
    }else {
        mark.alpha=1;
        [mark.tv becomeFirstResponder];
    }

    if (mark==nil) {
        float keyboardH=(self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)?352:262;
        NSLog(@"viewHeight====%f",htmlView.frame.size.height-keyboardH);
        mark=[[RemarkTable alloc] init];
//        mark.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.7];
        [self.view addSubview:mark];
        [mark release];
        [mark reFreshFrame:CGRectMake(0, 60, viewWidth, htmlView.frame.size.height-keyboardH-60)];
    }
       
}

-(void)popView{
    [self.navigationController popViewControllerAnimated:YES];
}



-(void)showList{
    if (list.alpha) {
        list.alpha=0;
    }else {
        list.alpha=1;
    }
    if (list==nil) {
        float keyboardH=(self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight)?352:262;
        list=[[ListTable alloc] initWithFrame:CGRectMake(0, 60, keyboardH, htmlView.frame.size.height-keyboardH)];
        list.delegate=self;
        list.imId=mgid;
        list.dataArray=[NSArray arrayWithArray:doc.forums];
        [self.view addSubview:list];
        [list release];
    }
    [list.table reloadData];
}

-(void)formPages{

}
-(void)initBottomView{
        bottomView=[[UIView alloc] init];
    if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        bottomView.frame=CGRectMake(0, 748-35,  viewWidth, bottomViewheight);
    }else {
        bottomView.frame=CGRectMake(0, 1004-35,  viewWidth, bottomViewheight);
        NSLog(@"HHHH");
    }

    bottomView.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.6];

    [self.view addSubview:bottomView];
    [self.view bringSubviewToFront:bottomView];

        [bottomView release];
        showBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        showBtn.frame=CGRectMake(10, 0, 35, 35);
        [showBtn setImage:[UIImage imageNamed:@"thumb.png"] forState:UIControlStateNormal];
        [showBtn addTarget:self action:@selector(bottomAnimate) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:showBtn];

        contents=[[UIScrollView alloc] init];
        contents.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"contents_bg.png"]];
        [bottomView addSubview:contents];
        [contents release];

    contents.frame=CGRectMake(0, 35,  viewWidth, 165);
    contents.delegate=self;
    contents.contentSize=CGSizeMake(dataArray.count*150, 165);
    int tcount=0;

    for (int i=0;i<doc.forums.count;i++) {
        Forum*f=[doc.forums objectAtIndex:i];
        for (int j=0;j<f.articles.count;j++ ) {
            Article* a=[f.articles objectAtIndex:j];
            for (int k=0;k<a.pages.count;k++) {
                Page*p=[a.pages objectAtIndex:k];
//               NSString* directory=[NSString stringWithFormat:@"Documents/0423"];
                NSString*imgPath=[NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/BookData/%@/%@",mgid,p.t_thumbnails]];
                imgPath=[imgPath stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];

//            NSString*imgPath=[NSHomeDirectory() stringByAppendingPathComponent:[directory stringByAppendingPathComponent:p.v_thumbnails]];
                NSData*da=[NSData dataWithContentsOfFile:imgPath];
                UIButton*b=[UIButton buttonWithType:UIButtonTypeCustom];
                b.tag=tcount;
                [b addTarget:self action:@selector(pageSelect:) forControlEvents:UIControlEventTouchUpInside];
                b.frame=CGRectMake(30+(120+30)*tcount, 30, 120, 95);
                [b setBackgroundImage:[UIImage imageWithData:da] forState:UIControlStateNormal];
                [contents addSubview:b];
                [thumbArray addObject:b];
                UILabel* label=[[UILabel alloc] initWithFrame:CGRectMake(30+(120+30)*tcount, 140, 120, 20)];
                label.text=a.title;
                label.textColor=[UIColor whiteColor];
                label.backgroundColor=[UIColor clearColor];
                [contents addSubview:label];
                [label release];
                [dataArray addObject:p];
                tcount++;
            }
        }
    }
    
}

-(void)selectThumb:(UIButton*)btn{
    for (UIButton* b in thumbArray) {
        if (b.tag==btn.tag) {
            b.selected=YES;
            b.layer.borderWidth=2;
            b.layer.borderColor=[[UIColor redColor] CGColor];
        }else {
            b.selected=NO;
            b.layer.borderWidth=0;
        }
    }

}
- (void)pageSelect:(UIButton*)btn{
    [self selectThumb:btn];
    [self setBookPage:btn.tag];
}

- (void)setBookPage:(NSInteger)index
{
    currentPage=index;
    Page* p=[dataArray objectAtIndex:currentPage];
    NSURLRequest*req;
    if (self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft||self.interfaceOrientation==UIInterfaceOrientationLandscapeRight) {
        req=[NSURLRequest requestWithURL:[self pathOfHtml:p.t_htmlref]];
    }else {
        req=[NSURLRequest requestWithURL:[self pathOfHtml:p.v_htmlref]];
    }
    [htmlView loadRequest:req];
}

-(void)bottomAnimate{    
    int h;
    if (viewWidth==1024) {
        h=748;
    }else {
        h=1004;
    }
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:0.3f];
    CGPoint p=bottomView.center;
    if (bottomView.center.y>h) {
        bottomView.center=CGPointMake(p.x, p.y-165);
    }else {
        bottomView.center=CGPointMake(p.x, p.y+165);

    }
    [UIView commitAnimations];
}


-(void)ShowBars:(UIGestureRecognizer*)recgongizer{
    [UIView beginAnimations:@"hiden" context:nil ];
    [UIView setAnimationCurve:UIViewAnimationCurveLinear];
    [UIView setAnimationDuration:0.3];
    if (topview.alpha) {
        topview.alpha=0;
        list.alpha=0;
        bottomView.alpha=0;

        int h;
        if (viewWidth==1024) {
            h=748;
        }else {
            h=1004;
        }
        CGPoint p=bottomView.center;
        if (bottomView.center.y<h) {
            bottomView.center=CGPointMake(p.x, p.y+165);
        }

    
    }else {
        topview.alpha=1;
        bottomView.alpha=1;
    }
    [UIView commitAnimations];

}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
   NSString* str=@"/H/";
    if (self.interfaceOrientation==UIInterfaceOrientationLandscapeRight||self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft) {
        
        
        if ([request.URL.absoluteString rangeOfString:str].location!=NSNotFound) {
            return YES;
        }else {
            return NO;
        }
    }else {
        if ([request.URL.absoluteString rangeOfString:str].location==NSNotFound) {
            return YES;
        }else {
            return NO;
        }

    }
    NSLog(@"shouldStartLoadWithRequest  ======%@",request);
}

-(void)webViewDidStartLoad:(UIWebView *)webView{

}

-(void)webViewDidFinishLoad:(UIWebView *)webView{


}
- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self copyBookToDoc];
    [self parseXML];

#if showType
    ascrollView=[[UIScrollView alloc] init];
    if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        ascrollView.frame=CGRectMake(0, 0, 1024, 768-20-self.navigationController.navigationBar.frame.size.height);
    }else {
       ascrollView.frame= CGRectMake(0, 0, 768, 1024-20-self.navigationController.navigationBar.frame.size.height);
    }
    ascrollView.delegate=self;
    ascrollView.pagingEnabled=YES;
    loop=webCount>dataArray.count?dataArray.count:webCount;
    ascrollView.contentSize=CGSizeMake(ascrollView.frame.size.width*loop, ascrollView.frame.size.height);
    for (int i=0; i<loop; i++) {
        UIWebView*web=[[UIWebView alloc] initWithFrame:CGRectMake(0+i*ascrollView.frame.size.width, 0, ascrollView.frame.size.width, ascrollView.frame.size.height)];
        Page* p=[dataArray objectAtIndex:i];
        NSArray* temp=[p.htmlref componentsSeparatedByString:@"."];
        NSString* path=[[NSBundle mainBundle]pathForResource:[temp objectAtIndex:0] ofType:[temp objectAtIndex:1]];
        NSURLRequest*req=[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path isDirectory:NO]];
        web.scalesPageToFit=YES;
        [web loadRequest:req];
        [ascrollView addSubview:web];
        [webArray addObject:web];
        [web release];
    }
    NSLog(@"%@",webArray);
    [self.view addSubview:ascrollView];
#else
    htmlView=[[UIWebView alloc] init];
    htmlView.delegate=self;
    if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        htmlView.frame=CGRectMake(0, 0, 1024, 768-20);
    }else {
        htmlView.frame= CGRectMake(0, 0, 768, 1024-20);
//        htmlname=[[dataArray objectAtIndex:0] htmlref];

    }
//    htmlView.backgroundColor=[UIColor redColor];
    [self viewWidth:self.interfaceOrientation];
    htmlView.scrollView.scrollEnabled=NO;

    [self.view addSubview:htmlView];
    UITapGestureRecognizer* tap1=[[UITapGestureRecognizer alloc] init];
    [htmlView addGestureRecognizer:tap1];
    tap1.delegate=self;
    [tap1 release];

    UISwipeGestureRecognizer* swipeRecongizer=[[UISwipeGestureRecognizer alloc] init];
    [htmlView addGestureRecognizer:swipeRecongizer];
    swipeRecongizer.delegate=self;
    [swipeRecongizer release];
    
    UISwipeGestureRecognizer* swipeGestureLeft=[[UISwipeGestureRecognizer alloc] init];
    swipeGestureLeft.direction=UISwipeGestureRecognizerDirectionLeft;
    swipeGestureLeft.delegate=self;
    [htmlView addGestureRecognizer:swipeGestureLeft];
    [swipeGestureLeft release];

#endif
    [self initTopView];
    [self initBottomView];
    Page* p0=[dataArray objectAtIndex:0];
    NSURLRequest*req;
    if(self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft||self.interfaceOrientation==UIInterfaceOrientationLandscapeRight){
        req=[NSURLRequest requestWithURL:[self pathOfHtml:p0.t_htmlref]];
    }else {
        req=[NSURLRequest requestWithURL:[self pathOfHtml:p0.v_htmlref]];
    }
    [htmlView loadRequest:req];
    htmlView.scalesPageToFit=YES;


}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
   
    if ([gestureRecognizer isKindOfClass:[UITapGestureRecognizer class]]) {
        [self ShowBars:gestureRecognizer];
        return YES;
    }

    CATransition *animation = [CATransition animation];
    animation.delegate = self;
    animation.duration = 0.5;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = kCATransitionReveal;
    UISwipeGestureRecognizer*recognizer=(UISwipeGestureRecognizer*)gestureRecognizer;
    if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
        animation.subtype = kCATransitionFromRight;
        currentPage++;
    }
    else if (recognizer.direction == UISwipeGestureRecognizerDirectionRight) {
        animation.subtype = kCATransitionFromLeft;
        currentPage--;
    }
    
    if (currentPage<0) {
        currentPage = 0;
    }
    else if(currentPage>[dataArray count]-1){
        currentPage = [dataArray count]-1;
    }
    else {
        Page*p=[dataArray objectAtIndex:currentPage];
        NSURLRequest*req;
        if (self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft||self.interfaceOrientation==UIInterfaceOrientationLandscapeRight) {
            req=[NSURLRequest requestWithURL:[self pathOfHtml:p.t_htmlref]];
        }else {
            req=[NSURLRequest requestWithURL:[self pathOfHtml:p.v_htmlref]];
        }
        [htmlView loadRequest:req];
        [[htmlView layer] addAnimation:animation forKey:@"animation"];
    }
    
//    UISwipeGestureRecognizer*recognizer=(UISwipeGestureRecognizer*)gestureRecognizer;
//    if (recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
//        NSLog(@"ShouldBegin to left");
//        if (currentPage+1<dataArray.count) {
//            [self animateWebView:1];
//        }
//
//    }
//    if (recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
//        NSLog(@"ShouldBegin to right");
//        if (currentPage>0) {
//            [self animateWebView:0];
//        }
//    }
//    Page*p=[dataArray objectAtIndex:currentPage];
//    NSURL*url=[self pathOfHtml:p.t_htmlref];
////    if (url==nil) {
////        [htmlPoint loadHTMLString:@"<html><head></head><body></body></html>" baseURL:nil];
////    }else {
//        NSURLRequest*req=[NSURLRequest requestWithURL:url];
//        [htmlPoint loadRequest:req];
////    }
    return NO;
}
/*
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    UISwipeGestureRecognizer*recognizer=(UISwipeGestureRecognizer*)gestureRecognizer;
    if (recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
        NSLog(@"from left");
        [self animateWebView:0];
        return NO;
    }
    if (recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        NSLog(@"from right");
        [self animateWebView:1];
        return NO;
    }
    return YES;
}
*/

/*
-(void)animateWebView:(int )type{
    CATransition *animation = [CATransition animation];
    
    animation.delegate = self;
    // 设定动画时间
    animation.duration = 0.7f;
    // 设定动画快慢(开始与结束时较慢)
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    switch (type) {
        case 0:
            animation.subtype = kCATransitionFromLeft;//滑动
            htmlPoint=htmlView;
            currentPage--;
//            animation.type=@"pageUnCurl";//翻页
            break;
        case 1:
            animation.subtype = kCATransitionFromRight;
            htmlPoint=htmlview1;
            currentPage++;
//            animation.type=@"pageCurl";//翻页
        default:
            break;
    }
    NSUInteger green = [[self.view subviews] indexOfObject:htmlView];
    NSUInteger blue = [[self.view subviews] indexOfObject:htmlview1];
    [self.view exchangeSubviewAtIndex:green withSubviewAtIndex:blue];
    [[self.view layer] addAnimation:animation forKey:@"animation"];

}
 */

-(NSURL*)pathOfHtml:(NSString*)htmlName{
    NSString* path= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/BookData/%@/%@",mgid,htmlName]];
    path=[path stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSURL* url=[NSURL fileURLWithPath:path];
       NSLog(@"html------%@",url);  
        return url;
    }else {
           NSLog(@"html------nil");
        return nil;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

//    currentPage= (int)scrollView.contentOffset.x/scrollView.frame.size.width;
    NSLog(@" didend===%d",currentPage);
//    [scrollView setContentOffset:CGPointMake(currentPage*scrollView.frame.size.width, 0) animated:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}


-(void)listTableSelectedPage:(Page*)pag{
    currentPage=[pag.num intValue];
    Page* p=[dataArray objectAtIndex:currentPage];
    NSURLRequest*req;
    if (self.interfaceOrientation==UIInterfaceOrientationLandscapeLeft||self.interfaceOrientation==UIInterfaceOrientationLandscapeRight) {
        req=[NSURLRequest requestWithURL:[self pathOfHtml:p.t_htmlref]];
    }else {
        req=[NSURLRequest requestWithURL:[self pathOfHtml:p.v_htmlref]];
    }
    [htmlView loadRequest:req];
}

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    [self viewWidth:toInterfaceOrientation];
    list.interfaceOrientation=toInterfaceOrientation;
    Page* p=[dataArray objectAtIndex:currentPage];

#if !showType    
    NSURLRequest*req;
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        req=[NSURLRequest requestWithURL:[self pathOfHtml:p.t_htmlref]];
        htmlView.frame=CGRectMake(0, 0, 1024, 768-20);
        bottomView.frame=CGRectMake(0, 748-35,  viewWidth, bottomViewheight);
    }else {
        req=[NSURLRequest requestWithURL:[self pathOfHtml:p.v_htmlref]];
        htmlView.frame= CGRectMake(0, 0, 768, 1024-20);
        bottomView.frame=CGRectMake(0, 1004-35,  viewWidth, bottomViewheight);
    }
    [htmlView loadRequest:req];
    float keyboardH=(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)?352:262;

    NSLog(@"%fkeyboardH===%f",htmlView.frame.size.height,keyboardH);
    [mark reFreshFrame:CGRectMake(0, 60, viewWidth, htmlView.frame.size.height-keyboardH-60)];
    contents.frame=CGRectMake(0, 35, viewWidth, 165);
    
    topview.frame=CGRectMake(0, 0, viewWidth, 55);
    UIButton* b=(UIButton*)[topview viewWithTag:111];
    b.frame=CGRectMake(viewWidth-80, 0, 40, 55);
    showBtn.frame=CGRectMake(10, 0, 35, 35);
    UIButton*markbtn=(UIButton*)[topview viewWithTag:222];
    markbtn.frame=CGRectMake(viewWidth-140, 0, 40, 55);

    UIButton* add=(UIButton*)[topview viewWithTag:333];
    add.frame=CGRectMake(viewWidth-200, 0, 40, 55);
    [htmlView reload];

#else
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        ascrollView.frame=CGRectMake(0, 0, 1024, 768-20-self.navigationController.navigationBar.frame.size.height);
    }else {
       ascrollView.frame= CGRectMake(0, 0, 768, 1024-20-self.navigationController.navigationBar.frame.size.height);
    }
    ascrollView.contentSize=CGSizeMake(ascrollView.frame.size.width*loop, ascrollView.frame.size.height);
    int p=(int)ascrollView.contentOffset.x/ascrollView.frame.size.width;
    [ascrollView setContentOffset:CGPointMake(p*ascrollView.frame.size.width, 0) animated:NO];
    NSLog(@"%d",currentPage);
    NSLog(@"content width %f",ascrollView.contentSize.width);
    NSLog(@"frame width %f",ascrollView.frame.size.width);
    for (int i=0; i<webArray.count;i++) {
        UIWebView* web=[webArray objectAtIndex:i];
        web.frame=CGRectMake(0+i*ascrollView.frame.size.width, 0, ascrollView.frame.size.width, ascrollView.frame.size.height);
        NSLog(@"%@",web);
        [web reload];
    }
#endif
    
    if (pov.popoverVisible) {
        [pov presentPopoverFromRect:[topview viewWithTag:111].frame inView:topview permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
    }

}
#pragma mark parser
//-(void)copyBookToDoc{
//   NSString* docPath= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/0423"];
//    NSString* bundlePath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"0423"];
//   BOOL b=[[NSFileManager defaultManager] copyItemAtPath:bundlePath toPath:docPath error:nil];
//
//}
-(void)parseXML{
//    NSString *xmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"xml" inDirectory:@"0423"];
NSString* xmlPath= [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/BookData/%@/index.xml",mgid]];
    NSXMLParser* parser=[[NSXMLParser alloc] initWithContentsOfURL:[NSURL fileURLWithPath:xmlPath]];
    parser.delegate=self;
    if ([parser parse]) {
        
    }
    [parser release];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    NSLog(@"elementName------%@",elementName);
    if ([elementName isEqualToString:@"Document"]) {
        doc=[[Document alloc] init];
        doc.total=[attributeDict valueForKey:@"total"];
    }
    if ([elementName isEqualToString:@"Forum"]) {
        forum=[[Forum alloc] init];
        forum.title=[attributeDict valueForKey:@"title"];
        forum.index=[attributeDict valueForKey:@"index"];
    }
    if ([elementName isEqualToString:@"Article"]) {
        article=[[Article alloc] init];
        article.title=[attributeDict valueForKey:@"title"];
        article.num=[attributeDict valueForKey:@"num"];
    }
    if ([elementName isEqualToString:@"Page"]) {
        page=[[Page alloc] init];
        page.t_enlarge=[attributeDict valueForKey:@"t-enlarge"];
        NSLog(@"page.t_enlarge------%@",page.t_enlarge);

        page.num=[attributeDict valueForKey:@"num"];
        page.t_htmlref=[attributeDict valueForKey:@"t-htmlref"];
        NSLog(@"t_htmlref------%@",page.t_htmlref);

        page.t_thumbnails=[attributeDict valueForKey:@"t-thumbnails"];
        NSLog(@"t_thumbnails------%@",page.t_thumbnails);

        page.v_enlarge=[attributeDict valueForKey:@"h-enlarge"];
        NSLog(@"page.v_enlarge------%@",page.v_enlarge);

        page.v_htmlref=[attributeDict valueForKey:@"h-htmlref"];
        NSLog(@"page.v_htmlref------%@",page.v_htmlref);

        page.v_thumbnails=[attributeDict valueForKey:@"h-thumbnails"];
        NSLog(@"page.v_thumbnails------%@",page.v_thumbnails);

    }
}



-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    NSLog(@"parse end===%@,%@,%@",elementName,namespaceURI,qName);
    if ([elementName isEqualToString:@"Page"]) {
        [article.pages addObject:page];
        [page release];
        page=nil;
        NSLog(@"%@",article.pages);
    }
    if ([elementName isEqualToString:@"Article"]) {
        [forum.articles addObject:article];
        [article release];
        article=nil;
    }
    if ([elementName isEqualToString:@"Forum"]) {
        [doc.forums addObject:forum];
        NSLog(@"%@",forum);
        [forum release];
        forum=nil;

    }
}
@end
